#!/bin/bash
 
. /etc/init.d/functions 
SRC_DIR=`pwd`
OPENSSH='openssh-8.6p1.tar.gz'
COLOR='echo -e \E[01;31m'
END='\E[0m'
 
check (){
 
if [ $UID -ne 0 ]; then
  action "当前用户不是root,安装失败" false
  exit 1
fi
 
cd  $SRC_DIR
if [ !  -e $OPENSSH ];then
        $COLOR"缺少${OPENSSH}文件"$END
        $COLOR"请将相关软件放在${SRC_DIR}目录下"$END
        exit
else
    return
fi
} 
 
install_OPENSSH(){
    $COLOR"开始安装OPENSSH..."$END
    #备份相关文件目录
    cp -r /etc/ssh /etc/ssh`date -I`
    cp -r /etc/pam.d /etc/pam.d`date -I`
    #rm -rf ssh_host_dsa_key*
    #rm -rf ssh_host_ecdsa_key*
    #rm -rf ssh_host_rsa_key*
    #rm -rf ssh_host_ed25519_key*
    $COLOR"安装依赖包"$END
    yum install  -y gcc gcc-c++ glibc make autoconf openssl openssl-devel pcre-devel  pam-devel pam* zlib* &> /dev/null
    cd $SRC_DIR
    #将原始包解压到/usr/local/下
    tar xf $OPENSSH -C /usr/local/
    #取出原始包的版本号   
    #OPENSSH_DIR=`echo $OPENSSH| sed -nr 's/^(.*[0-9]).*/\1/p'`
    $COLOR"编译安装"$END
    chown -R root.root /usr/local/openssh-8.6p1
    cd /usr/local/openssh-8.6p1
    ./configure &> /dev/null    
    make && make install &> /dev/null
    #替换程序文件
    mv /usr/bin/ssh /usr/bin/ssh`date -I`
    cp /usr/local/bin/ssh /usr/bin/ssh
    mv /usr/sbin/sshd /usr/sbin/sshd`date -I`
    cp /usr/local/sbin/sshd /usr/sbin/sshd
    #设置允许root远程登录
    sed -i "s/no/yes/g" /etc/ssh/sshd_config
    #拷贝解压包中相关文件到目标位置
    cp -a contrib/redhat/sshd.init /etc/init.d/sshd
    cp -a contrib/redhat/sshd.pam /etc/pam.d/sshd.pam
    chmod +x /etc/init.d/sshd
    chkconfig --add sshd
    systemctl enable sshd
    #移除systemd管理的sshd文件
    mv  /usr/lib/systemd/system/sshd.service  /tmp/
    #设置sshd服务开机启动
    chkconfig sshd on
    #设置sshroot登录
    sed -i '48s#$#&/\n        OPTIONS="-f /etc/ssh/sshd_config"#g' /etc/init.d/sshd
    #系统重新加载启动文件
    systemctl daemon-reload
    #重启sshd
    /etc/init.d/sshd restart
    $COLOR"OPENSSH安装完成"$END
}
 
check
 
install_OPENSSH